package com.hellobike.haxing.modules.coupon.service.impl;

import com.hellobike.haxing.common.util.DateUtils;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.coupon.entity.Coupon;
import com.hellobike.haxing.modules.coupon.entity.UserCoupon;
import com.hellobike.haxing.modules.coupon.mapper.CouponMapper;
import com.hellobike.haxing.modules.coupon.mapper.UserCouponMapper;
import com.hellobike.haxing.modules.coupon.service.ICouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description: 优惠券
 * @Author: haxing-boot
 * @Date:   2020-02-01
 * @Version: V1.0
 */
@Service
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements ICouponService {
    @Autowired
    private UserCouponMapper userCouponMapper;
    @Override
    public List<Coupon> getByIds(List<Long> idList) {
        List<Coupon> couponList = baseMapper.selectBatchIds(idList);
        //按照原参数中顺序排序
        Map<Long, Coupon> couponMap = couponList.stream().collect(Collectors.toMap(Coupon::getId, Function.identity()));
        couponList = idList.stream().map(id -> couponMap.get(id)).filter(o -> o != null).collect(Collectors.toList());
        return couponList;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void returnUserCoupon(Long userCouponId) {
        UserCoupon userCoupon = userCouponMapper.selectById(userCouponId);
        if (userCoupon == null) {
            return ;
        }
        //券已使用且未过期则返还，否则不返还
        if (userCoupon.getStatus() == 1 && userCoupon.getExpireTime().isAfter(LocalDateTime.now())) {
            //更新券状态为未使用，清除用券订单号
            UserCoupon updateModel = new UserCoupon();
            updateModel.setId(userCouponId);
            updateModel.setStatus(0);
            updateModel.setOrderNo("");
            userCouponMapper.updateById(updateModel);
        }
    }

}
